package weightmanager;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Queue;

/**
 * 
 * @author Lasse Poulsen
 * 
 */
public class TCPClientThread extends Thread {
	private DataOutputStream outputStream;
	private BufferedReader inputStream;
	private Queue<String> inputQueue;
	private Queue<String> outputQueue;
	private boolean running = true;

	/**
	 * Thread for managing I/O with the socket connection streams from
	 * {@link TCPClient}
	 * 
	 * @param inFromServer
	 * @param outToServer
	 * @param inQ
	 * @param outQ
	 * @param crlf
	 */
	public TCPClientThread(BufferedReader inFromServer, DataOutputStream outToServer,
			Queue<String> inQ, Queue<String> outQ) {
		inputStream = inFromServer;
		inputQueue = inQ;
		outputStream = outToServer;
		outputQueue = outQ;
	}

	
	/**
	 * Overrides the interrupt interface in Thread
	 */
	public void interrupt() {
		try {
			outputStream.close();
			inputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		this.running = false;
	}

	public void run() {
		while (running) {
			String input = "";
			try {
				synchronized (inputQueue) {
					while (inputStream.ready()) {
						input += String.valueOf((char) inputStream.read());
					}
					if (input.length() > 0) {
						input = input.replaceAll("\r\n", "");
						inputQueue.add(input);
						System.err.println("INP: " + input);
					}
				}
			} catch (IOException e1) {
				e1.printStackTrace();
			}

			try {
				synchronized (outputQueue) {
					while (!outputQueue.isEmpty()) {
						String out = outputQueue.poll();
						System.err.println("OUT: " + out);
						outputStream.writeBytes(out + "\r\n");
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}